package com.ucode.wap.cgms.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ucode.cgms.api.CgmsSysConfigRemoteApi;
import com.ucode.cgms.service.CgmsGiftRewardOrderService;
import com.ucode.cgms.service.CgmsGiftService;
import com.ucode.model.cgms.CgmsGift;
import com.ucode.model.cgms.CgmsGiftRewardOrder;
import com.ucode.model.cgms.convert.CgmsGiftRewardOrderConvert;
import com.ucode.model.cgms.enums.CgmsGiftStateEnum;
import com.ucode.model.cgms.enums.CgmsPayStateEnum;
import com.ucode.model.cgms.enums.CgmsRewardTypeEnum;
import com.ucode.model.cgms.enums.CgmsSysResultCodeEnum;
import com.ucode.model.cgms.form.CgmsGiftRewardOrderForm;
import com.ucode.model.pay.order.dto.PayOrderCreateReqDTO;
import com.ucode.pay.service.PayOrderService;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.base.enums.UserTypeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import com.ucode.tool.util.ServletUtils;
import com.ucode.wap.base.core.CurrentLoginUserHandler;
import com.ucode.wap.cgms.service.ApiCgmsGiftRewardOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class ApiCgmsGiftRewardOrderServiceImpl implements ApiCgmsGiftRewardOrderService {

    @Resource
    private CgmsGiftRewardOrderService cgmsGiftRewardOrderService;
    @Resource
    private CgmsGiftService cgmsGiftService;
    @Resource
    private CgmsSysConfigRemoteApi cgmsSysConfigRemoteApi;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private CurrentLoginUserHandler currentLoginUserHandler;

    @Override
    public Long submitOrder(CgmsGiftRewardOrderForm form) {

        //创建订单
        CgmsGiftRewardOrder bean = CgmsGiftRewardOrderConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());
        bean.setRewardUserId(currentLoginUserHandler.getCurrentUserId());
        bean.setCompanionUserId(form.getCompanionUserId());
        BigDecimal price = BigDecimal.ZERO;
        //根据类型计算金额 打赏类型(1:礼物打赏,2:自定义打赏)
        if (ObjectUtil.equals(bean.getRewardType(), CgmsRewardTypeEnum.GIFT_REWARD.getCode())){
            //验证礼物信息
            if (ObjUtil.isNotEmpty(form.getGiftId())){
                CgmsGift gift = cgmsGiftService.validate(form.getGiftId());
                if(ObjUtil.equals(gift.getStatus(), CgmsGiftStateEnum.OFF_SHELF.getCode())){
                    throw new UcodeServiceException(CgmsSysResultCodeEnum.GIFT_NOT_EXISTS);
                }
                bean.setAmount(NumberUtil.mul(gift.getPrice(),bean.getQuantity()));
            }
        }

        bean.setPayState(CgmsPayStateEnum.AWAIT.getState());
        //订单失效时间默认15分钟
        bean.setExpireTime(LocalDateTimeUtil.offset(LocalDateTimeUtil.now(),30, ChronoUnit.MINUTES));
        Long orderId = cgmsGiftRewardOrderService.insert(bean);
        //6、生成统一支付订单
        String userIp = ServletUtils.getClientIP();
        Long merchantOrderNo = orderId;
        Integer amount = NumberUtil.mul(bean.getAmount(),100).intValue();
        String serviceNotifyUrl = cgmsSysConfigRemoteApi.getGiftRewardOrderPayNotifyUrl();
        Long payOrderId = createPayOrder(form.getPayAppId(), bean.getRewardUserId(), UserTypeEnum.MEMBER.getCode(), userIp, merchantOrderNo.toString(), amount, bean.getExpireTime(), serviceNotifyUrl);

        //默认支付通过（测试环境）,切记后续要删掉
        //paySuccess(orderId,payOrderId, PayTypeEnum.WX_LITE.getCode(),LocalDateTime.now(),amount);

        return payOrderId;
    }

    @Override
    public void paySuccess(Long orderId, Long payOrderId, String payType, LocalDateTime payTime, Integer payAmount) {
        cgmsGiftRewardOrderService.paySuccess(orderId, payOrderId,payType , payTime,payAmount);
    }

    @Override
    public void delete(Long orderId) {
        Long userId = currentLoginUserHandler.getCurrentUserId();
        cgmsGiftRewardOrderService.deleteByMember(userId,orderId);
    }

    /**
     * 创建支付订单
     * @param appId
     * @param userId
     * @param userType
     * @param userIp
     * @param merchantOrderNo
     * @param amount
     * @param expireTime
     * @param serviceNotifyUrl
     * @return 支付订单ID
     */
    private Long createPayOrder(Long appId, Long userId, Integer userType, String userIp, String merchantOrderNo, Integer amount, LocalDateTime expireTime, String serviceNotifyUrl) {
        // 创建支付单，用于后续的支付
        PayOrderCreateReqDTO payOrderCreateReqDTO = new PayOrderCreateReqDTO();
        payOrderCreateReqDTO.setAppId(appId);
        payOrderCreateReqDTO.setUserId(userId);
        payOrderCreateReqDTO.setUserType(userType);
        payOrderCreateReqDTO.setUserIp(userIp);
        payOrderCreateReqDTO.setMerchantOrderNo(merchantOrderNo);
        payOrderCreateReqDTO.setSubject("打赏支付");
        payOrderCreateReqDTO.setBody("");
        payOrderCreateReqDTO.setCurrency("CNY");
        payOrderCreateReqDTO.setAmount(amount);
        payOrderCreateReqDTO.setExpireTime(expireTime);
        payOrderCreateReqDTO.setServiceNotifyUrl(serviceNotifyUrl);
        Long payOrderId =  payOrderService.create(payOrderCreateReqDTO);
        if(ObjUtil.isNull(payOrderId)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.FAILED.getCode(), "提交支付失败,请稍后重试");
        }
        return payOrderId;
    }

}
